/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.jastrzab.service;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;

/**
 *
 * @author Jastrzab
 */
public abstract class BindActivity extends Activity implements ServiceConnection {

	private Messenger mService = null;
	private final Messenger mMessenger = new Messenger(new ReciveHandler());
	private boolean isBound = false;

	public void onServiceConnected(ComponentName className, IBinder service) {
		mService = new Messenger(service);
		sendHandler(Message.obtain(null, BindSevice.REGISTER_CLIENT));
		onAddService(mService);
	}

	public void onServiceDisconnected(ComponentName arg0) {
		mService = null;
		onRemoveService();
	}

	protected boolean bindService(Context context, Class<?> target) {
		return bindService(context, target, 0);
	}

	protected boolean bindService(Context context, Class<?> target, int bindFlag) {
		try {
			return getApplicationContext().bindService(new Intent(context, target), this, bindFlag);
		} finally {
			isBound = true;
		}
	}

	protected void unbindService() {
		if (isBound) {
			if (mService != null) {
				sendHandler(Message.obtain(null, BindSevice.REMOVE_CLIENT, isFinishing()));
			}
			getApplicationContext().unbindService(this);
			isBound = false;
		}
	}

	public void sendHandler(Message message) {
		try {
			message.replyTo = mMessenger;
			mService.send(message);
		} catch (Exception e) {

		}
	}

	private final class ReciveHandler extends Handler {

		@Override
		public void handleMessage(Message message) {
			switch (message.what) {
				default:
					onReciveHandler(message);
			}
		}

	}

	public void onAddService(Messenger service) {

	};

	public void onRemoveService() {

	};

	protected abstract void onReciveHandler(Message message);

}
